

import 'dart:convert';
import 'dart:io';

import 'package:rms_mobile_client/Bloc/Storage/IDataContext.dart';
import 'package:rms_mobile_client/Bloc/Storage/IDataContext.dart';
import 'package:rms_mobile_client/Bloc/Storage/IDataContext.dart';
import 'package:rms_mobile_client/Entities/MyApp.dart';
import 'package:rms_mobile_client/Entities/User.dart';
import 'package:rms_mobile_client/StateManagement/ModelProvider.dart';
import 'package:rms_mobile_client/StateManagement/ObservableList.dart';
import 'package:path_provider/path_provider.dart';

class LocalJsonDataContext extends IDataContext {
  final String HOME_DIR = "Rms-Mobile-Client/";
  String path;

  @override
  Future<void> load() async {
    Directory dir;
    if (Platform.isAndroid) dir = await getExternalStorageDirectory();
    else dir = await getTemporaryDirectory();
    path = dir.path;
    path = "$path/$HOME_DIR";
    dir = Directory(path);
    if (!await dir.exists()) await dir.create();

    if (!await dir.exists()) await dir.create();
    /******************************************************/

    //region *Users*/
    var usersFromLocal = await _readFromLocal("users.json");
    usersFromLocal.forEach((user) => users.add(User.fromJson(user)));
    this.users.notifier.addListener((){
      _writeToLocal(this.users.map((user) => user.toJson()).toList(), "users.json");
    });
    //endregion

    applyChanges();
  }

  Future<void> _writeToLocal(Object obj, String fileName) async {
    print("********Write $fileName begin ****************");
    var sourceFilePath = "$path$fileName";
    var tempFilePath = "$path$fileName-TEMP";
    var backupFilePath = "$path$fileName-local-${DateTime.now().toIso8601String()}";

    var tempFile = File(tempFilePath);
    if (!await tempFile.exists()) tempFile = await tempFile.create();

    var json = jsonEncode(obj);
    tempFile = await tempFile.writeAsString(json, mode: FileMode.write);
    var orginalFile = File(sourceFilePath);
    if (await orginalFile.exists()) await orginalFile.rename(backupFilePath);
    await tempFile.rename(sourceFilePath);
  }

  Future<List<dynamic>> _readFromLocal(String fileName) async {
    var sourceFilePath = "$path$fileName";
    var file = File(sourceFilePath);
    if (!await file.exists()) return [];
    var jsonText = await file.readAsString();
    var result = jsonDecode(jsonText);
    return result;
  }
}
